package com.ruoyi.mq

import lombok.extern.slf4j.Slf4j
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ThreadPoolExecutor

@Slf4j
@Component
class ScheduledService {

    @Autowired
    private lateinit var changeFaceTaskService: ChangeFaceTaskService

    @Autowired
    private lateinit var delayQueueManager: DelayQueueManager

    @Autowired
    private lateinit var changeFaceTask: ThreadPoolExecutor


    private val log = LoggerFactory.getLogger(ScheduledService::class.java)


    @Scheduled(cron = "0/5 * * * * *")
    fun scheduled() {
        val currentTime = System.currentTimeMillis()
        val expiredItems: Set<String> = delayQueueManager.getExpiredItems(currentTime)

        expiredItems.takeIf { it.isNotEmpty() }?.run {
            log.info("扫描到换脸任务 ${joinToString(";")}")
        }

        //启动一个线程执行当前任务
        CompletableFuture.runAsync({
            expiredItems.takeIf { it.isNotEmpty() }?.forEach {
                delayQueueManager.removeItems(setOf(it))
                changeFaceTaskService.scheduleTask(it.toLong())
            }

        }, changeFaceTask)
    }
}